<!--
 * @Author: Wangtao
 * @Date: 2020-10-22 19:27:39
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-11-19 16:22:57
-->
<template>
  <drawer-box>
    <template v-slot:content>
      <el-form
        class="m7-form"
        :label-position="labelPosition"
        :rules="rules"
        :model="formData"
        size="mini"
        ref="nodeForm"
      >
        <el-form-item label="节点名称" prop="name">
          <el-input v-model.trim="formData.name" size="mini" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="分支" prop="name">
          <template v-slot:label>
            <span>
              分支
              <el-tooltip
                :show-after="500"
                class="item"
                effect="dark"
                content="分支可以拖动排序，路由判断按照分值从上到下的顺序执行，如有重复则执行较前的分值分配。"
                placement="top"
              >
                <span class="MC_iconfont MC_icon-yiwen-mian tip-span"></span>
              </el-tooltip>
              <span style="float: right">{{ formData.routes ? formData.routes.length : 0 }}/10</span>
            </span>
          </template>
          <draggable v-model="formData.routes">
            <!-- <div v-for="(item, index) in formData.routes" :key="index + 'model'">
              <model
                :ref="index + 'model'"
                :data="item"
                :cascadeList="cascadeList"
                :condition="condition[index + 1]"
                @delBranch="delBranch"
                :id="index"
                :nodeList="nodeList"
                :currentData="currentData"
              />
            </div> -->
            <template #item="{ element, index }">
              <model
                :key="index + 'model'"
                :ref="index + 'model'"
                :data="element"
                :cascadeList="cascadeList"
                :condition="condition[index + 1]"
                @delBranch="delBranch"
                :id="index"
                :nodeList="nodeList"
                :currentData="currentData"
              />
            </template>
          </draggable>
        </el-form-item>
        <span @click="addBranch" style="cursor: pointer"
          ><i class="MC_iconfont MC_icon-tianjia-xian add-span"></i>添加分支</span
        >

        <el-form-item style="margin-top: 20px" label="其他">
          <el-select
            v-if="condition[0]"
            v-model="condition[0].to"
            placeholder="请选择下一步节点"
            clearable
            filterable
            style="width: 100%; margin-top: 10px"
          >
            <el-option
              v-for="(node, index) in nodeList"
              :label="node.data.name"
              :value="node.id"
              v-show="!node.viewOnly && node.id !== currentData.id && node.id !== 'startNode'"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:operation>
      <el-button @click="cancel" size="mini">取消</el-button>
      <el-button type="primary" @click="onSave" size="mini">确定</el-button>
    </template>
    <template v-slot:remove>
      <el-button @click="deleteNode" type="danger" :icon="Delete" size="mini">删除</el-button>
    </template>
  </drawer-box>
</template>

<script lang="ts" setup>
import model from './model/model.vue'
import draggable from 'vuedraggable'
import drawerBox from '@/app/call-center/components/drawer-box.vue'
import { withDefaults, defineProps, ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import useNodeCommon from './use-node-common'
import { Delete } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import http from '@/common/utils/http'
import { ElMessage } from 'element-plus'
const nodeForm: any = ref(null)
const props = withDefaults(
  defineProps<{
    data: any
    currentNode: any
    save: (...arg: any) => void
    cancel: () => void
    delete: (...arg: any) => void
  }>(),
  {
    data: {},
    currentNode: {}
  }
)
const { nodeList, currentData, labelPosition, rules, formData, condition, cancel, onSubmit, deleteNode }: any =
  useNodeCommon({
    data: props.data,
    currentNode: props.currentNode,
    nodeForm,
    save: props.save,
    cancel: props.cancel,
    delete: props.delete
  })

type State = {
  publicList: any
}
const state: State = reactive({
  publicList: []
})

const _this: any = getCurrentInstance()

const customParametersList: any = computed(() => {
  const arr = cloneDeep(props.data.nodeList)
  const list = arr.find((item: any) => item.id === 'startNode').data?.customList?.filter((i: any) => i.key) || []
  for (let i = 0; i < list.length; i++) {
    const element = list[i]
    element.memo = `${element.key} ${element.memo}`
  }
  return list
})

const cascadeList: any = computed(() => {
  // 参数级联数据
  const list = [
    {
      key: 'fixed',
      memo: '系统参数',
      children: state.publicList
    },
    {
      key: 'custom',
      memo: '自定义参数',
      children: customParametersList.value
    }
  ]
  return customParametersList.value?.length ? list : list.filter((_: any, index: number) => index === 0)
})

const getPublicCustom = () => {
  const url = '/call/web/call/action/config/ivr/system-var/cache'
  http({ url, method: 'get' }).then((res) => {
    if (res.success) {
      state.publicList = res.data || []
    }
  })
}

onMounted(() => getPublicCustom())

const addBranch = () => {
  if (formData.value.routes.length >= 10) {
    ElMessage.error('分支不能超过10个')
    return
  }
  condition.value.push({ label: `分支${formData.value.routes.length + 1}`, to: '', value: '' })
  formData.value.routes.push({
    name: `分支${formData.value.routes.length + 1}`,
    operator: 'and',
    next: '',
    conditions: [{ k: '', op: '', v: '' }],
    condition: { label: `分支${formData.value.routes.length + 1}`, to: '', value: '' }
  })
}

const delBranch = (index: number) => {
  if (formData.value.routes && formData.value.routes.length <= 1) {
    ElMessage.error('分支不能少于1个')
    return
  }
  formData.value.routes.splice(index, 1)
}

const onSave = async () => {
  let num = 0
  for (let i = 0; i < formData.value.routes.length; i++) {
    const item: any = _this.refs[i + 'model']
    await item.form.validate((valid: any) => {
      if (valid) {
        num++
      }
    })
  }
  condition.value.splice(1)
  formData.value.routes.forEach((e: any, index: number) => {
    condition.value[index + 1] = e.condition
    e.conditions.forEach((q: any) => {
      if (!Array.isArray(q.v)) {
        q.v = [q.v]
      }
    })
  })
  if (num === formData.value.routes.length) {
    onSubmit()
  }
}
// eslint-disable-next-line no-undef
defineExpose({
  form: nodeForm
})
</script>

<style lang="stylus" scoped>
  .audioProgress
    margin 0 10px 0
  .tip-span
    color $icon-gray
    cursor pointer
    margin-left 4px
    font-size 14px
.add-span
  font-size 12px
  cursor pointer
  &:before
    margin-right 4px
</style>
